import { Component } from 'react'

import './app.scss'

import Taro from '@tarojs/taro'
import { getTime, isWechat } from './utils'
import GlobalData from './global';
const CONFIG = require('./config')

import { loginApi, refreshLoginApi } from './services/Login'
import { Logger } from './Logger';


class App extends Component {

  updateUserInfo(nickname:string, avatar:string) {
    GlobalData.userInfo.nickName = nickname
    GlobalData.userInfo.avatar = avatar

    Taro.setStorage({
        key : CONFIG.USER_INFO_STOREAGE_KEY,
        data : {...GlobalData.userInfo}
    })
  }

  loginComplete(data) {
    const { accessToken, refreshToken, expire } = data
    process.env.access_token = data.accessToken
    let time = getTime()
    let params = {
        access_token : accessToken,
        refresh_token : refreshToken,
        expire_in : time + expire, //登陆有效期
    }

    GlobalData.isLogin = true
    GlobalData.token = accessToken
    process.env.access_token = accessToken

    Taro.setStorage({
      key : CONFIG.ACCESS_INFO_STOREAGE_KEY,
      data : params
    })

    this.refreshLogin(expire - 300)


    this.updateUserInfo(data.nickname || '', data.avatar || '')
    
  }

  async login(params) {
    Taro.showLoading({mask:true, title : '加载中'})
    let result = await loginApi(params)
    Logger.info('登录请求结果', result)
    Taro.hideLoading()
    if(result.success) {
      this.loginComplete(result.data)
    }else {
        Taro.showModal({title : '登陆失败'})
    }
  }

  refreshLogin(time) { //刷新登录
    setTimeout(async () => {
      Taro.getStorage({
        key : CONFIG.ACCESS_INFO_STOREAGE_KEY,
        async success(res) {
          let result = await refreshLoginApi(res.data.refresh_token)
          if(result.success) {
            this.loginComplete(result.data)
          }
        }
      })
      
    }, time * 1000)
  }

  wxLogin() {
    Taro.login({
      success : res => {
        Logger.info('Taro.login success', res)
        if (res.code) {
          this.login({code : res.code, partnerId : CONFIG.partnerId, grantType : CONFIG.grantType})
        }
      },
      fail(e) {
        Logger.error('Taro.login fail', e)
      }
    })
  }

  

  componentDidMount () {
    GlobalData.clientType = isWechat() ? 1 : 2

    if(isWechat()) { //微信小程序
      let accessInfo = Taro.getStorageSync(CONFIG.ACCESS_INFO_STOREAGE_KEY)
      if(!accessInfo) { //登陆
        this.wxLogin()
      }else { //判断微信session有无过期
        Taro.checkSession({
          success : () => {
            let time = getTime() //当前时间
            let offsetTime = accessInfo.expire_in - time //剩余还有多久过期
            if(offsetTime < 600) { //距离过期时间小于10分钟，重新登录
              this.wxLogin()
            }else {
              process.env.access_token = accessInfo.access_token
              GlobalData.isLogin = true
              GlobalData.token = accessInfo.access_token
              this.refreshLogin(offsetTime - 300) //5分钟之后刷新
            }
          },

          fail: () => {
            this.wxLogin()
          }
        })
      }
    }

    Taro.getStorage({key : CONFIG.USER_INFO_STOREAGE_KEY})
    .then(res => {
      let data = res.data
      if(data) {
        GlobalData.userInfo.nickName = data.nickName
        GlobalData.userInfo.avatar = data.avatar
      }
    })
    .catch(err => {
      console.log(err)
    })
    
  }

  componentDidShow () {}

  componentDidHide () {}

  componentDidCatchError () {}

  // this.props.children 是将要会渲染的页面
  render () {
    return this.props.children
  }
}

export default App
